/*
 * Project: equity
 *
 * File Created at 2020-08-11
 *
 * Copyright 2016 CMCC Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ZYHY Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license.
 */
package cn.lxh.basic.utils;

import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Type UUIDUtils.java
 * @Desc
 * @author xieweihua
 * @date 2020-08-11 18:28
 * @version
 */
public class UUIDUtils {
    private static AtomicInteger counter = new AtomicInteger(0);
    private static final int CLUSTER;


    /**
     *
     */
    static {
        String clusterConfig = System.getProperty("cluster");
        if (!StringUtils.isEmpty(clusterConfig)) {
            CLUSTER = Integer.parseInt(clusterConfig) & 0xff;
        } else {
            try {
                CLUSTER = (InetAddress.getLocalHost().getAddress()[3]) & 0xff;
            } catch (UnknownHostException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 获取序列码
     */
    public static Long nextId() {
        // 时间 | 8位集群编号 | 16位循环计数器
        long stamp = System.currentTimeMillis();
        return (stamp >> 10 << 24) | (CLUSTER << 16) | (nextSeq(counter) & 0xffff);
    }

    /**
     * 获取序列码
     * @param prefix 序列前缀
     */
    public static String nextId(String prefix) {
        // 时间 | 8位集群编号 | 16位循环计数器
        long stamp = System.currentTimeMillis();
        Long value = (stamp >> 10 << 24) | (CLUSTER << 16) | (nextSeq(counter) & 0xffff);
        return prefix + value;
    }

    /**
     * 长度为32为的uuid
     * 生产随机字符串 ，如：c9f94e8fc68d4fbe9f424e8540fc8316  不包含"-"
     */
    public static String getUUID() {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return uuid;
    }

    /**
     * nextSeq 下一个序列值
     * @param atomicInteger
     * @return
     */
    private static int nextSeq(AtomicInteger atomicInteger) {
        return atomicInteger.incrementAndGet();
    }

}
